import axios from 'axios'
import Router from '@/router'
import { removeToken, getToken } from '@/utils/auth'

import { Message } from 'element-ui'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true,
  timeout: 500000
})

// axios请求拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    console.log('请求配置中的responseType:', config.responseType) // 打印responseType确认是否传递
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// axios响应拦截器
service.interceptors.response.use(res => {
    // 获取错误信息
    const msg = res.data.msg
    const data = res.data
    console.log(res.request.responseType)
    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      console.log(res.request.responseType)
      return res // 直接返回响应对象，确保前端能获取到Blob数据
    }
   if (data.code === 200) {
      return data
    } else if (data.code === 500) {
      Message({ message: msg, type: 'error' })
    } else if (data.code === 600) {
      Message({ message: msg, type: 'warning' })
    } else {
      Message({ message: msg, type: 'warning' })
    }
    return Promise.reject(msg)
  },

  error => {
    const code = error.response.status
    let { message } = error
    console.log(code)
    if (code === 401) {
      Message({ message: '登录状态已过期请重新登录', type: 'warning', duration: 2000 })
      setTimeout(() => {
        removeToken()
        Router.replace('/login')
      })
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    }
    else if (message == 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    Message({ message: message, type: 'error' })

    return Promise.reject(error)
  })

export default service
